import { parse } from '@/utils/historyUtils';
import { setToken } from '@/utils/token';
import { useModel } from '@umijs/max';
import { Spin } from 'antd';
import React, { useEffect } from 'react';
import { history } from 'umi';

export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const goto = async () => {
    if (!history) return;

    // 如果不是登录页面，执行
    const { location } = history;

    console.log('====================', location);

    // 如果没有登录，重定向到 login
    const { token, route } = parse(location.search) as {
      token: string;
      route: string;
    };
    console.log('===token===', token);

    if (token) {
      setToken(token);
      // const route = location.search.replace('?route=', '');
      // const route = '/interview'
      console.log('==1=route===', route);
      const userInfo = await initialState?.fetchUserInfo?.();
      if (userInfo) {
        setInitialState({
          ...initialState,
          currentUser: userInfo,
        });
        setTimeout(() => {
          if (history.replaceState) {
            history.replaceState(null, document.title, route);
            history.go(0);
          } else {
            history.replace(route);
          }
        }, 100);
      }

      window.addEventListener('message', function (e) {
        if (e.data.route) {
          history.push(e.data.route);
        }
      });
    } else {
      // const route = location.search.replace('?route=', '');
      console.log('==2=route===', route);
      let state = btoa(`{"access":"pc","type":"route","route":"${route}"}`);
      console.log('===state===', state);
      history.push(
        `https://auth-moc.ljsyy.net/oauth/authorize?client_id=GDRM&response_type=code&redirect_uri=https://xtbs.ljsyy.net/xtbs/app/login/loginAppForSpreadBrain&state=${state}`,
      );
    }
  };

  useEffect(() => {
    goto();
  }, []);

  return (
    <div
      style={{
        textAlign: 'center',
        marginTop: 20,
        marginBottom: 20,
      }}
    >
      <Spin size="large" />
    </div>
  );
};
